package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.StringTools;
import com.example.demo.common.UserSessionTools;
import com.example.demo.entity.ArticleInfo;
import com.example.demo.entity.CommentInfo;
import com.example.demo.entity.UserInfo;
import com.example.demo.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @RequestMapping("/submit")
    public AjaxResult add(CommentInfo commentInfo, HttpServletRequest request){
        System.out.println(commentInfo+"===="+commentInfo.getContent());
        //1.非空验证
        if (commentInfo == null || !StringUtils.hasLength(commentInfo.getContent()))
            return AjaxResult.fail(-1, "参数异常!");
        //2.得到uid 组装数据
        UserInfo userInfo = UserSessionTools.getLoginUser(request);
        if (userInfo == null){
            return AjaxResult.fail(-1, "参数异常!");
        }
        commentInfo.setUid(userInfo.getId());
        commentInfo.setCreatetime(LocalDateTime.now());
        //持久化数据
        int result = commentService.add(commentInfo);
        return AjaxResult.success(result);
    }
    @RequestMapping("/init")
    public AjaxResult initComment(Integer article_id){
        List<CommentInfo> commentInfos = commentService.initComment(article_id);
        return AjaxResult.success(commentInfos);
    }
}
